import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class TheEntrance {
	static private ArrayList<String> AllClassNames = new ArrayList<String>();
	static public void main (String args[]) {
		System.out.println("--------main start--------");
		String entranceName = null;
		showClass();
		entranceName = getEntrance();
		System.out.println("--------------------------");
		
		long startrun = System.currentTimeMillis();
		execute(entranceName);
		long endrun = System.currentTimeMillis();
		System.out.println("--------main end----------");
		System.out.println("time spent: "+(endrun-startrun));
	}

	static private void showClass () {
		System.out.println(FieldUpLine);
		System.out.println("now list the classes in the folder \"entrance\":");
		File f = new File("src/entrance");
		try {
			String[] x = f.list();
			Arrays.sort(x, String.CASE_INSENSITIVE_ORDER);
			for (int i=0;i<x.length;i++) {
				System.out.printf("%2d: %s%n", i, x[i]);
				if (x[i].endsWith(".java")) 
					AllClassNames.add(x[i].substring(0, x[i].lastIndexOf(".")));
			}
		}
		catch (Exception e) {
			System.err.println("error in show class");
			e.printStackTrace();
			System.exit(1);
		}
		System.out.println(FieldDownLine);
	}
	
	static private String getEntrance() {
		System.out.println("please choose the class to start: ");
		String className="";
		try {
			className = (new Scanner (System.in)).nextLine();
			if (className.matches("\\d+?")) {
				int id = Integer.parseInt(className);
				if (id<AllClassNames.size() && id>=0)
					return "entrance."+AllClassNames.get(id);
				else {
					System.err.println("invalid number!");
				}
			}
			else {
				return className;
			}
		}
		catch(Exception e) {
			System.err.println("error in get the entrance");
			e.printStackTrace();
		}
		System.exit(1);
		return null;
	}
	
	static private void execute(String className) {
		try {
			Object o = Class.forName(className).newInstance();
			if (o instanceof Runnable) {
				((Runnable)o).run();
			}
			else {
				System.err.println("The class '"+className+"' does not implement runnable!");
			}
		}
		catch(Exception e) {
			System.err.println("catch error in main");
			e.printStackTrace();
		}
	}
	
	static private String FieldUpLine = "________________________________________";
	static private String FieldDownLine = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
}

